package com.yt.Insurance.server.api.client;

import com.yt.Insurance.models.dto.InsurancePolicyDTO;
import com.yt.Insurance.models.vo.InsurancePolicyVO;
import com.yt.Insurance.models.bo.PolicyQueryBO;
import com.yt.Insurance.models.service.InsurancePolicyService;
import com.github.pagehelper.PageInfo;
import com.yt.common.constant.Result;
import com.yt.common.constant.CommonParameter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 小程序端保险投保接口
 */
@RestController
@RequestMapping("/api/policy")
public class InsurancePolicyController {

    @Autowired
    private InsurancePolicyService policyService;

    /**
     * 用户创建投保单
     */
    @PostMapping
    public Result<InsurancePolicyVO> createPolicy(@Valid @RequestBody InsurancePolicyDTO policyDTO, 
                                                          HttpServletRequest request) {
        try {
            // 从请求头中获取当前登录用户的ID
            String userIdStr = request.getHeader("userId");
            if (userIdStr == null || userIdStr.isEmpty()) {
                // 尝试从请求参数中获取userId
                userIdStr = request.getParameter("userId");
                if (userIdStr == null || userIdStr.isEmpty()) {
                    // 尝试从CommonParameter中获取sessionId，再从中解析userId
                    userIdStr = CommonParameter.getHeadParamsBO().getSessionId();
                    if (userIdStr == null || userIdStr.isEmpty()) {
                        return Result.fail("未授权访问");
                    }
                }
            }
            
            policyDTO.setUserId(Long.valueOf(userIdStr));
            InsurancePolicyVO policyVO = policyService.createPolicy(policyDTO);
            return Result.success(policyVO);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("服务器内部错误");
        }
    }

    /**
     * 查询保单详情（公开接口，无需权限验证）
     */
    @GetMapping("/{policyId:[0-9]+}")
    public Result<InsurancePolicyVO> getPolicyDetail(@PathVariable Integer policyId) {
        System.out.println("开始查询保单详情，policyId: " + policyId);
        try {
            // 查询保单详情（无需权限验证）
            InsurancePolicyVO policyVO = policyService.getPolicyById(policyId);
            
            if (policyVO == null) {
                System.out.println("未找到保单ID为" + policyId + "的保单");
                return Result.fail("未找到保单");
            }
            
            System.out.println("成功获取保单详情: " + policyVO);
            return Result.success(policyVO);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("服务器内部错误");
        }
    }

    /**
     * 分页查询当前用户保单
     */
    @GetMapping("/my-policies")
    public Result<PageInfo<InsurancePolicyVO>> getMyPolicies(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            HttpServletRequest request) {
        try {
            // 从请求头中获取当前登录用户的ID
            String userIdStr = request.getHeader("userId");
            if (userIdStr == null || userIdStr.isEmpty()) {
                // 尝试从请求参数中获取userId
                userIdStr = request.getParameter("userId");
                if (userIdStr == null || userIdStr.isEmpty()) {
                    // 尝试从CommonParameter中获取sessionId，再从中解析userId
                    userIdStr = CommonParameter.getHeadParamsBO().getSessionId();
                    if (userIdStr == null || userIdStr.isEmpty()) {
                        return Result.fail("未授权访问");
                    }
                }
            }
            
            // 构造查询条件
            PolicyQueryBO queryBO = new PolicyQueryBO();
            queryBO.setPageNum(pageNum);
            queryBO.setPageSize(pageSize);
            queryBO.setUserId(Long.valueOf(userIdStr)); // 添加用户ID过滤条件
            
            PageInfo<InsurancePolicyVO> pageInfo = policyService.queryPolicyPage(queryBO);
            return Result.success(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("服务器内部错误");
        }
    }

    /**
     * 退保接口
     */
    @PostMapping("/{policyId:[0-9]+}/surrender")
    public Result<String> surrenderPolicy(@PathVariable Integer policyId,
                                          @RequestParam(required = false) String surrenderReason,
                                          @RequestParam(required = false) java.math.BigDecimal refundAmount,
                                          HttpServletRequest request) {
        try {
            // 查询保单详情（取消用户权限验证）
            InsurancePolicyVO policyVO = policyService.getPolicyById(policyId);
            
            // 不再验证该保单是否属于当前用户
            if (policyVO == null) {
                return Result.fail("未找到保单");
            }
            
            boolean success = policyService.surrenderPolicy(policyId, surrenderReason, refundAmount);
            if (success) {
                return Result.success("退保成功");
            } else {
                return Result.fail("退保失败，保单不存在或不可退保");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("服务器内部错误");
        }
    }
}